package com.corx.network.mysqlstorage.common;

import java.util.ArrayList;
import java.util.List;

/**
 * @author gx
 * @version 1.0.0
 */
public class SqlQueryBuilder {

    private final String baseSql;
    private final List<String> conditions = new ArrayList<>();
    private final List<Object> params = new ArrayList<>();
    private String orderBy;

    public SqlQueryBuilder(String baseSql) {
        this.baseSql = baseSql;
    }

    public static SqlQueryBuilder from(String baseSql) {
        return new SqlQueryBuilder(baseSql);
    }

    public SqlQueryBuilder whereEquals(String column, Object value) {
        if (value != null) {
            conditions.add(column + " = ?");
            params.add(value);
        }
        return this;
    }

    public SqlQueryBuilder whereLike(String column, String value) {
        if (value != null && !value.trim().isEmpty()) {
            conditions.add(column + " LIKE ?");
            params.add("%" + value.trim() + "%");
        }
        return this;
    }

    public SqlQueryBuilder whereGt(String column, Object value) {
        if (value != null) {
            conditions.add(column + " > ?");
            params.add(value);
        }
        return this;
    }

    public SqlQueryBuilder whereGte(String column, Object value) {
        if (value != null) {
            conditions.add(column + " >= ?");
            params.add(value);
        }
        return this;
    }

    public SqlQueryBuilder whereLt(String column, Object value) {
        if (value != null) {
            conditions.add(column + " < ?");
            params.add(value);
        }
        return this;
    }

    public SqlQueryBuilder whereLte(String column, Object value) {
        if (value != null) {
            conditions.add(column + " <= ?");
            params.add(value);
        }
        return this;
    }

    public SqlQueryBuilder orderBy(String orderByClause) {
        if (orderByClause != null && !orderByClause.trim().isEmpty()) {
            this.orderBy = orderByClause;
        }
        return this;
    }

    public String getSql() {
        StringBuilder sb = new StringBuilder(baseSql);
        if (!conditions.isEmpty()) {
            sb.append(" WHERE ").append(String.join(" AND ", conditions));
        }
        if (orderBy != null) {
            sb.append(" ORDER BY ").append(orderBy);
        }
        return sb.toString();
    }

    public Object[] getParams() {
        return params.toArray();
    }
}
